package org.example.service;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.example.annotation.MetricTime;
import org.example.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

@Component
@ConditionalOnProperty(name = "app.smtp", havingValue = "true")
public class MailService {

    @Autowired(required = false)
    @Qualifier("zdy")
    private ZoneId zoneId = ZoneId.systemDefault();


    @Value("#{smtpConfig.host}")
    private String smtpHost;

    @Value("#{smtpConfig.port}")
    private String smtpPort;

    public String getTime() {
        return ZonedDateTime.now(this.zoneId).format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
    }

    @MetricTime("sendLoginMail")
    public void sendLoginMail(User user) {
        System.err.println(String.format("Hi,%s!You are logged in at %s", user.getName(), getTime()));
    }

    public void sendRegisterMail(User user) {
        System.err.println(String.format("Hi,%s!You are registered at %s", user.getName(), getTime()));
    }

    @PostConstruct
    public void init() {
        System.out.println("Init mail service with zoneId = " + this.zoneId);
        System.out.println("smtpHost = " + smtpHost);
        System.out.println("smtpPort = " + smtpPort);
    }

    @PreDestroy
    public void shutdown() {
        System.out.println("Shutdown mail service");
    }
}
